package com.sunshine.monitor.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.List;

public class JVMMemory implements IJVMMemory {

	private static final JVMMemory memory = new JVMMemory();

	// Code Cache
	// Eden Space
	// Survivor Space
	// Tenured Gen
	// Perm Gen
	// Perm Gen [shared-ro]
	// Perm Gen [shared-rw]

	private MemoryPoolMXBean edenSpace;
	private MemoryPoolMXBean survivorSpace;
	private MemoryPoolMXBean oldSpace;
	private MemoryPoolMXBean permSpace;
	private MemoryUsage heapSpace;

	public JVMMemory() {

		List<MemoryPoolMXBean> list = ManagementFactory.getMemoryPoolMXBeans();
		for (MemoryPoolMXBean m : list) {
			String name = m.getName();
			if ("Eden Space".equals(name)) {
				edenSpace = m;
			} else if ("Survivor Space".equals(name)) {
				survivorSpace = m;
			} else if ("Tenured Gen".equals(name)) {
				oldSpace = m;
			} else if ("Perm Gen".equals(name)) {
				permSpace = m;
			}

		}

		heapSpace = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

	}

	public static JVMMemory getInstance() {
		return memory;
	}

	public long getMemoryUsed() {
		return heapSpace.getUsed();
	}

	public long getMemoryMax() {
		return heapSpace.getMax();
	}

	public long getEdenUsed() {
		return edenSpace.getUsage().getUsed();
	}

	public long getEdenMax() {
		return edenSpace.getUsage().getMax();
	}

	public long getSurvivorUsed() {
		return survivorSpace.getUsage().getUsed();
	}

	public long getSurvivorMax() {
		return survivorSpace.getUsage().getMax();
	}

	public long getOldUsed() {
		return oldSpace.getUsage().getUsed();
	}

	public long getOldMax() {
		return oldSpace.getUsage().getMax();
	}

	public long getPermUsed() {
		return permSpace.getUsage().getUsed();
	}

	public long getPermMax() {
		return permSpace.getUsage().getMax();
	}

	public long getHeapUsed() {
		return heapSpace.getUsed();
	}

	public long getHeapMax() {
		return heapSpace.getMax();
	}

}
